package com.dongnao.jack.invocate;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import com.dongnao.jack.loadbalance.BalanceFactory;
import com.dongnao.jack.loadbalance.NodeRegisterInfo;
import com.dongnao.jack.spring.parse.ProtocolConfig;
import com.dongnao.jack.spring.parse.ReferenceConfig;

/**
 * 
 * @ClassName: RegistryInvocationHandler 
 * @Description: 用于proxy 动态代理
 * @author xuyp
 * @date 2018年4月19日 上午10:14:23 
 *
 */
public class RegistryInvocationHandler implements InvocationHandler {

    private RegistryInvocate invaocate;

    private ReferenceConfig reference;

    public RegistryInvocationHandler(RegistryInvocate invaocate, ReferenceConfig reference) {
        super();
        this.invaocate = invaocate;
        this.reference = reference;
    }

    @SuppressWarnings("static-access")
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        NodeRegisterInfo registerInfo = BalanceFactory.getBalance(reference.getLoadbalance())
                .getRegisterInfo(reference.getRegisterList(), reference.getProtocol());

        // JSONObject parseObject = JSONObject.parseObject(registerInfo.toString());
        // ProtocolConfig protocol = registerInfo.get;
        ProtocolConfig bean = reference.getApplicationContext().getBean(ProtocolConfig.class);

        return reference.invocates.get(bean.getName())
                .invoke(new RegistryInvocation(method, args, reference, registerInfo));
    }

}
